package com.github.defense.starter.zuul.configuration;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.github.defense.common.config.DefenseConfig;
import com.github.defense.plugin.base.DefensePlugin;
import com.github.defense.starter.common.configuration.DefenseCommonAutoConfiguration;
import com.github.defense.starter.zuul.filter.PluginPreZuulFilter;
import com.github.defense.starter.zuul.launch.DefenseRegisterProcessor;
import com.github.defense.sync.data.api.PluginSubscriber;
import com.github.defense.sync.data.nacos.NacosSyncDataService;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.List;
import java.util.Objects;

/**
 * @Author: lettger
 * @Date: 2021/12/13 上午10:03
 */
@Configuration
@ImportAutoConfiguration(DefenseCommonAutoConfiguration.class)
public class ZuulAutoConfiguration {

    /**
     * 网关注册到defense admin后台
     *
     * @param config
     * @param environment
     * @param applicationEventPublisher
     * @return
     */
    @Bean
    public DefenseRegisterProcessor defenseRegisterProcessor(final ObjectProvider<DefenseConfig>  config, final Environment environment, final ApplicationEventPublisher applicationEventPublisher) {
        return new DefenseRegisterProcessor(Objects.requireNonNull(config.getIfAvailable()), environment, applicationEventPublisher);
    }

    /**
     * defense 后台数据变更 通过Nacos来同步
     * @param nacosConfigProperties
     * @return
     * @throws NacosException
     */
    @Bean
    public NacosSyncDataService nacosSyncDataService(final ObjectProvider<NacosConfigProperties> nacosConfigProperties,ObjectProvider<PluginSubscriber> subscriber) throws NacosException {
        return new NacosSyncDataService(NacosFactory.createConfigService(Objects.requireNonNull(nacosConfigProperties.getIfAvailable()).assembleConfigServiceProperties()),subscriber.getIfAvailable());
    }

    @Bean
    public PluginPreZuulFilter pluginPreZuulFilter(final ObjectProvider<List<DefensePlugin>> plugins){
        return new PluginPreZuulFilter(Objects.requireNonNull(plugins.getIfAvailable()));
    }
}
